rm(list = ls())
library(ggplot2)
library(randomForest)
library(dplyr)
library(forcats)
setwd("./Replication")
source("Code/figure_setup.R")

############################################################################
##                Figure 1 
############################################################################
# Load RF Results to make  Figure 1
load("Results/RF_base.RData")
# create a data from the RF model for variable importance
data <- as.data.frame(cbind(rownames(RF_base$importance),round(RF_base$importance[,"IncNodePurity"],1)))
colnames(data) <- c("Parameters","IncNodePurity")
data$IncNodePurity <- as.numeric(as.character(data$IncNodePurity))
# re-ordering
data <- data %>% 
    dplyr::mutate(name = fct_reorder(Parameters, IncNodePurity)) 

###  Plot Figure 1
ggplot(data, aes(IncNodePurity,name)) + geom_point() +
      xlab("Mean Decrease in Node Impurity") + ylab("")+
      scale_y_discrete(labels = c("High democracy, change",
                                  "Low democracy, change",
                                  "Trade dependence, change",
                                  "High democracy",
                                  "High number of BAAD groups",
                                  "GDP ratio, change",
                                  "Low democracy",
                                  "Military expenditures ratio",
                                  "Military personnel ratio",
                                  "GDP ratio",
                                  "High Regime durability",
                                  "Low Regime durability", 
                                  "High State fragility index",
                                  "Trade dependence",
                                  "Military personnel ratio, change",
                                  "Cooperative events",
                                  "Ideal point distance, change",
                                  "Low GDP per capita (log)",
                                  "Low number of BAAD groups",
                                  "Military expenditures ratio, change",
                                  "High GDP per capita (log)",
                                  "Low State fragility index",
                                  "Conflictual events",
                                  "Ideal point distance",
                                  "Minimum distance (log)",
                                  "Cumulative cooperative events",
                                  "Cumulative conflictual events",
                                  "Degree centrality(actor A)",
                                  "Degree centrality(actor B)" 
      )) + 
      theme_bw() + ggtitle("Random Forest Model") + 
      theme(axis.text= element_text(size=15),
      text = element_text(size=15))
ggsave("Figure/Figure_1.pdf", width =11, height = 12)
############################################################################
rm(RF_base, data)
############################################################################

#############################################################################
##                     Figure 2
############################################################################
##                Figure 2-b ##########
load("Results/basket_spdm.RData")
##### make coefficient for SPDM model
basket_spdm_coef <- plot_spdm_coef2(basket_spdm, 
                    variables = c("miliexp_ratio","delta_miliexp_ratio","milperson_ratio","delta_milperson_ratio",
                                  "idealpointdistance","delta_idealpointdistance", "high_GDPPC_log",
                                  "llow_GDPPC_log","ratio_GDP","delta_ratio_GDP",
                                  "low_democracy","high_democracy","delta_low_democracy",
                                  "delta_high_democracy","regime_dur_max","regime_dur_min",
                                  "sfi_high", "sfi_low",
                                  "verbCoop_cum","matlCoop_cum","verbConf_cum","matlConf_cum",
                                  "verbCoop", "verbConf","matlCoop","matlConf",
                                  "lnminidist","ccode1_degree", "ccode2_degree","(Intercept)"))

spdm_crisis_dur <- basket_spdm_coef[[1]]
results_df  <- spdm_crisis_dur$data 
results_df <- results_df %>% 
                rename(term = vars, 
                      estimate = beta,
                      std.error = se )
results_df$term <- as.character(results_df$term)
# Draw dot-and-whisker plot
p <- dwplot(results_df, show_intercept = TRUE,
            dot_args = list(color = "black",size = 2,shape = 17),
            whisker_args = list(color = "black", size = 1),
            order_vars =  c("miliexp_ratio","delta_miliexp_ratio","milperson_ratio","delta_milperson_ratio",
                            "idealpointdistance","delta_idealpointdistance", "high_GDPPC_log",
                            "llow_GDPPC_log","ratio_GDP","delta_ratio_GDP",
                            "low_democracy","high_democracy","delta_low_democracy",
                            "delta_high_democracy","regime_dur_max","regime_dur_min",
                            "sfi_high", "sfi_low",
                            "verbCoop_cum","matlCoop_cum","verbConf_cum","matlConf_cum",
                            "verbCoop", "verbConf","matlCoop","matlConf",
                            "lnminidist","(Intercept)"))+ theme_bw() +
  scale_y_discrete(labels=rev(c( "Military expenditures ratio",
                                 "Military expenditures ratio, change",
                                 "Military personnel ratio",
                                 "Military personnel ratio, change",
                                 "Ideal point distance",
                                 "Ideal point distance, change",
                                 "High GDP per capita (log)",
                                 "Low GDP per capita (log)",
                                 "GDP ratio",
                                 "GDP ratio, change",## first set of variavbles
                                 "Low democracy",
                                 "High democracy",
                                 "Low democracy, change",
                                 "High democracy, change",
                                 "High Regime durability",
                                 "Low Regime durability", # second set
                                 "High State fragility index",
                                 "Low State fragility index", #third set
                                 "Cumulative verbal cooperation",
                                 "Cumulative material cooperation",
                                 "Cumulative verbal conflict",
                                 "Cumulative material conflict","Verbal cooperation",
                                 "Verbal conflict",
                                 "Material cooperation",
                                 "Material conflict",# fourth set
                                 "Minimum distance (log)", 
                                 "(Intercept)"
  )))+
  theme(legend.position="none",
        legend.title=element_blank(),
        axis.text = element_text(size=14),
        text = element_text(size=14),
        plot.title = element_text(hjust = .5, size = 14, face = "bold")) + xlab("") +
  geom_vline(xintercept = 0, colour = "black", linetype = 2) +
  ggtitle("Duration: crisis occurrence (1995-2017)") 

# Add brackets
p_dur <- p %>% 
  add_brackets(list(c("Rise and decline of Power", "miliexp_ratio", "delta_ratio_GDP"), 
                   c("Regime entrenchment", "low_democracy", "regime_dur_min"),
                   c("Stateness", "sfi_high", "sfi_low"),
                   c("Action-level","verbCoop_cum", "matlConf"),
                   c("Dependeceies", "lnminidist", "(Intercept)")),
                  face = "bold") 

ggsave("Figure/Figure_2b_dur.eps", p_dur, width = 13, height = 11,dpi = 400)
############################################################################
##               Figure 2-a
############################################################################
spdm_crisis_risk <- basket_spdm_coef[[2]]
results_df  <- spdm_crisis_risk$data 
results_df <- results_df %>% 
              rename(term = vars, 
                      estimate = beta,
                      std.error = se )
results_df$term <- as.character(results_df$term)
# Draw dot-and-whisker plot
p <- dwplot(results_df, show_intercept = TRUE,
            dot_args = list(color = "black",size = 2,shape = 17),
            whisker_args = list(color = "black", size = 1),
            order_vars =  c("miliexp_ratio","delta_miliexp_ratio","milperson_ratio","delta_milperson_ratio",
                            "idealpointdistance","delta_idealpointdistance", "high_GDPPC_log",
                            "llow_GDPPC_log","ratio_GDP","delta_ratio_GDP",
                            "low_democracy","high_democracy","delta_low_democracy",
                            "delta_high_democracy","regime_dur_max","regime_dur_min",
                            "sfi_high", "sfi_low",
                            "verbCoop_cum","matlCoop_cum","verbConf_cum","matlConf_cum",
                            "verbCoop", "verbConf","matlCoop","matlConf",
                            "lnminidist","ccode1_degree", "ccode2_degree","(Intercept)"))+
          theme_bw() +
          scale_y_discrete(labels=rev(c( "Military expenditures ratio",
                                         "Military expenditures ratio, change",
                                         "Military personnel ratio",
                                         "Military personnel ratio, change",
                                         "Ideal point distance",
                                         "Ideal point distance, change",
                                         "High GDP per capita (log)",
                                         "Low GDP per capita (log)",
                                         "GDP ratio",
                                         "GDP ratio, change",## first set of variavbles
                                         "Low democracy",
                                         "High democracy",
                                         "Low democracy, change",
                                         "High democracy, change",
                                         "High Regime durability",
                                         "Low Regime durability", # second set
                                         "High State fragility index",
                                         "Low State fragility index", #third set
                                         "Cumulative verbal cooperation",
                                         "Cumulative material cooperation",
                                         "Cumulative verbal conflict",
                                         "Cumulative material conflict","Verbal cooperation",
                                         "Verbal conflict",
                                         "Material cooperation",
                                         "Material conflict",# fourth set
                                         "Minimum distance (log)", 
                                         "Degree centrality(actor A)",
                                         "Degree centrality(actor B)" ,
                                         "(Intercept)")))+
                  theme(legend.position="none",
                        legend.title=element_blank(),
                        axis.text = element_text(size=14),
                        text = element_text(size=14),
                        plot.title = element_text(hjust = .5, size = 12, face = "bold")) +
                  xlab("") +
                  geom_vline(xintercept = 0, colour = "black", linetype = 2) +
                  ggtitle("Risk: crisis occurrence (1995-2017)") 
# Add brackets
p_risk <- p %>% 
        add_brackets(list(c("Rise and decline of Power", "miliexp_ratio", "delta_ratio_GDP"), 
                          c("Regime entrenchment", "low_democracy", "regime_dur_min"),
                          c("Stateness", "sfi_high", "sfi_low"),
                          c("Action-level","verbCoop_cum", "matlConf"),
                          c("Dependeceies", "lnminidist", "(Intercept)")),
                         face = "bold") 
ggsave("Figure/Figure_2a_risk.eps",p_risk, width = 13, height = 11,dpi = 400)
############################################################################
rm(basket_spdm, basket_spdm_coef,p,p_dur, p_risk, results_df, spdm_crisis_dur,spdm_crisis_risk)
#############################################################################


#############################################################################
###              Figure 3
#############################################################################
# load model results for making Figure 3
load("Results/basket_spdmlowpolity.RData")
basket_spdm_coef <- plot_spdm_coef2(basket_spdmlowpolity, 
                              variables = c("miliexp_ratio","delta_miliexp_ratio","milperson_ratio","delta_milperson_ratio",
                                            "idealpointdistance","delta_idealpointdistance", "high_GDPPC_log",
                                            "llow_GDPPC_log","ratio_GDP","delta_ratio_GDP",
                                            "low_democracy","high_democracy","delta_low_democracy",
                                            "delta_high_democracy","regime_dur_max","regime_dur_min",
                                            "sfi_high", "sfi_low",
                                            "verbCoop_cum","matlCoop_cum","verbConf_cum","matlConf_cum",
                                            "verbCoop", "verbConf","matlCoop","matlConf",
                                            "lnminidist","ccode1_degree", "ccode2_degree","(Intercept)"))

spdm_crisis_dur <- basket_spdm_coef[[1]]
results_df  <- spdm_crisis_dur$data 
results_df <- results_df %>% 
            rename(term = vars, 
                  estimate = beta,
                  std.error = se )
results_df$term <- as.character(results_df$term)
# Draw dot-and-whisker plot
p <- dwplot(results_df, show_intercept = TRUE,
            dot_args = list(color = "black",size = 2,shape = 17),
            whisker_args = list(color = "black", size = 1),
            order_vars =  c("miliexp_ratio","delta_miliexp_ratio","milperson_ratio","delta_milperson_ratio",
                            "idealpointdistance","delta_idealpointdistance", "high_GDPPC_log",
                            "llow_GDPPC_log","ratio_GDP","delta_ratio_GDP",
                            "low_democracy","high_democracy","delta_low_democracy",
                            "delta_high_democracy","regime_dur_max","regime_dur_min",
                            "sfi_high", "sfi_low",
                            "verbCoop_cum","matlCoop_cum","verbConf_cum","matlConf_cum",
                            "verbCoop", "verbConf","matlCoop","matlConf",
                            "lnminidist","(Intercept)"))+ 
            theme_bw() +
            scale_y_discrete(labels=rev(c( "Military expenditures ratio",
                                           "Military expenditures ratio, change",
                                           "Military personnel ratio",
                                           "Military personnel ratio, change",
                                           "Ideal point distance",
                                           "Ideal point distance, change",
                                           "High GDP per capita (log)",
                                           "Low GDP per capita (log)",
                                           "GDP ratio",
                                           "GDP ratio, change",## first set of variavbles
                                           "Low democracy",
                                           "High democracy",
                                           "Low democracy, change",
                                           "High democracy, change",
                                           "High Regime durability",
                                           "Low Regime durability", # second set
                                           "High State fragility index",
                                           "Low State fragility index", #third set
                                           "Cumulative verbal cooperation",
                                           "Cumulative material cooperation",
                                           "Cumulative verbal conflict",
                                           "Cumulative material conflict","Verbal cooperation",
                                           "Verbal conflict",
                                           "Material cooperation",
                                           "Material conflict",# fourth set
                                           "Minimum distance (log)", 
                                           "(Intercept)")))+
                theme(legend.position="none",
                      legend.title=element_blank(),
                      axis.text = element_text(size=14),
                      text = element_text(size=14),
                      plot.title = element_text(hjust = .5, size = 12, face = "bold")) + xlab("") +
                geom_vline(xintercept = 0, colour = "black", linetype = 2) +
                ggtitle("Duration: crisis occurrence (1995-2017)") 
# Add brackets
p_dur <- p %>% 
    add_brackets(list(c("Rise and decline of Power", "miliexp_ratio", "delta_ratio_GDP"), 
                     c("Regime entrenchment", "low_democracy", "regime_dur_min"),
                     c("Stateness", "sfi_high", "sfi_low"),
                     c("Action-level","verbCoop_cum", "matlConf"),
                     c("Dependeceies", "lnminidist", "(Intercept)")),
                    face = "bold") 
ggsave("Figure/Figure_3b_dur.eps", p_dur, width = 13, height = 11,dpi = 400)
#############################################################################
                  # Figure 3-a
#############################################################################
spdm_crisis_risk <- basket_spdm_coef[[2]]
results_df  <- spdm_crisis_risk$data 
results_df <- results_df %>% 
            rename(term = vars, 
                  estimate = beta,
                  std.error = se )
results_df$term <- as.character(results_df$term)
# Draw dot-and-whisker plot
p <- dwplot(results_df, show_intercept = TRUE,
            dot_args = list(color = "black",size = 2,shape = 17),
            whisker_args = list(color = "black", size = 1),
            order_vars =  c("miliexp_ratio","delta_miliexp_ratio","milperson_ratio","delta_milperson_ratio",
                            "idealpointdistance","delta_idealpointdistance", "high_GDPPC_log",
                            "llow_GDPPC_log","ratio_GDP","delta_ratio_GDP",
                            "low_democracy","high_democracy","delta_low_democracy",
                            "delta_high_democracy","regime_dur_max","regime_dur_min",
                            "sfi_high", "sfi_low",
                            "verbCoop_cum","matlCoop_cum","verbConf_cum","matlConf_cum",
                            "verbCoop", "verbConf","matlCoop","matlConf",
                            "lnminidist","ccode1_degree", "ccode2_degree","(Intercept)"))+ 
          theme_bw() +
          scale_y_discrete(labels=rev(c( "Military expenditures ratio",
                                         "Military expenditures ratio, change",
                                         "Military personnel ratio",
                                         "Military personnel ratio, change",
                                         "Ideal point distance",
                                         "Ideal point distance, change",
                                         "High GDP per capita (log)",
                                         "Low GDP per capita (log)",
                                         "GDP ratio",
                                         "GDP ratio, change",## first set of variavbles
                                         "Low democracy",
                                         "High democracy",
                                         "Low democracy, change",
                                         "High democracy, change",
                                         "High Regime durability",
                                         "Low Regime durability", # second set
                                         "High State fragility index",
                                         "Low State fragility index", #third set
                                         "Cumulative verbal cooperation",
                                         "Cumulative material cooperation",
                                         "Cumulative verbal conflict",
                                         "Cumulative material conflict","Verbal cooperation",
                                         "Verbal conflict",
                                         "Material cooperation",
                                         "Material conflict",# fourth set
                                         "Minimum distance (log)", 
                                         "Degree centrality(actor A)",
                                         "Degree centrality(actor B)" ,
                                         "(Intercept)")))+
              theme(legend.position="none",
                    legend.title=element_blank(),
                    axis.text = element_text(size=14),
                    text = element_text(size=14),
                    plot.title = element_text(hjust = .5, size = 12, face = "bold")) + 
              xlab("") +
              geom_vline(xintercept = 0, colour = "black", linetype = 2) +
              ggtitle("Risk: crisis occurrence (1995-2017)") 
# Add brackets
p_risk <- p %>%
        add_brackets(list(c("Rise and decline of Power", "miliexp_ratio", "delta_ratio_GDP"), 
                          c("Regime entrenchment", "low_democracy", "regime_dur_min"),
                          c("Stateness", "sfi_high", "sfi_low"),
                          c("Action-level","verbCoop_cum", "matlConf"),
                          c("Dependeceies", "lnminidist", "(Intercept)")),
                          face = "bold") 
ggsave("Figure/Figure_3a_risk.eps", p_risk, width = 13, height = 11,dpi = 400)
#############################################################################
rm(basket_spdmlowpolity, basket_spdm_coef,p,p_dur, p_risk, results_df, spdm_crisis_dur,spdm_crisis_risk)
#############################################################################

    